<template>
  <XenPageLayout
    title="新增应聘申请"
    title-align="left"
    navbar-bg-color="#7881de"
    navbar-text-color="#ffffff"
    navbar-icon-color="#ffffff"
    contentStyle="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 0; height: 100vh; display: flex; flex-direction: column;"
  >
    <!-- 表单内容区域 -->
    <view class="form-container">
      <XenDynamicFormCard
        title="填写应聘申请信息"
        subtitle="请填写完整应聘申请信息以便审批"
        :sections="formSections"
        :modelValue="formData"
        :errors="formErrors"
        :showFooter="false"
        :idCardExpiryDisplayState="idCardExpiryDisplayState"
        @update:modelValue="handleFormDataChange"
        @fieldBlur="handleFieldBlur"
        @pickerChange="handlePickerChange"
        @datetimeChange="handleDateTimeChange"
        @imageUpload="handleImageUpload"
        @imageSuccess="handleImageSuccess"
        @imageFail="handleImageFail"
        @imageDelete="handleImageDelete"
        @fileUpload="handleFileUpload"
        @fileSuccess="handleFileSuccess"
        @fileFail="handleFileFail"
        @fileDelete="handleFileDelete"
        @departmentPickerChange="handleDepartmentPickerChange"
        @departmentPickerOpen="handleDepartmentPickerOpen"
        @departmentPickerClose="handleDepartmentPickerClose"
        @autoCompleteChange="handleAutoCompleteChange"
        @autoCompleteSearch="handleAutoCompleteSearch"
      />
    </view>

    <!-- 固定底部操作按钮 -->
    <XenFormActions
      :actions="formActions"
      :hidden="isDepartmentPickerOpen"
      @action="handleFormAction"
    />
  </XenPageLayout>
</template>

<script setup lang="ts">
import { onMounted, ref, computed } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import XenPageLayout from "@/layouts/XenPageLayout.vue";
import XenDynamicFormCard from "@/components/XenDynamicFormCard.vue";
import XenFormActions from "@/components/XenFormActions.vue";
import {
  getFormSectionsByPageType,
  getFilteredFormSections,
} from "./form-config";
import { useInterviewInfo } from "./composables/useInfo";
// 导入统一事件系统
import { InterviewInfoEvents } from "@/utils/eventBus";
// 导入文件上传函数
import { uploadImage } from "@/utils/unirequest";
// 导入API
import SysHrInterviewRequestBillApi from "./api/index";

// 创建API实例
const api = SysHrInterviewRequestBillApi();

// 获取新增页面的表单分组
const baseFormSections = getFormSectionsByPageType("create");

// 动态过滤表单字段（支持条件显示）
const formSections = computed(() => {
  return getFilteredFormSections(baseFormSections, formData);
});

// 部门选择器打开状态
const isDepartmentPickerOpen = ref<boolean>(false);

// 表单操作按钮配置
const formActions = computed(() => [
  {
    key: "cancel",
    label: "取消",
    type: "default" as const,
  },
  {
    key: "submit",
    label: "保存",
    type: "primary" as const,
  },
]);

// 使用应聘申请信息 Composable
const {
  formData,
  formErrors,
  pickerValues,
  validateField,
  handlePickerChange,
  handleDateTimeChange,
  initializeOptions,
  createInterview,
  saveInterviewSimple,
  search,
  getBillCode,
  recognizeIdentityCard,
  idCardExpiryDisplayState,
} = useInterviewInfo();

// 表单数据变化处理
const handleFormDataChange = (newData: Record<string, any>) => {
  Object.assign(formData, newData);

  // 特殊处理退伍军人字段
  if (newData.hasOwnProperty("isVeteran")) {
    const isVeteranValue = newData.isVeteran;
    // 如果选择否，清空退伍证图片
    if (isVeteranValue === "否" || !isVeteranValue) {
      formData.veteranCertificateId = null;
    }
  }

  // 特殊处理亲属关系字段
  if (newData.hasOwnProperty("hasRelativeInCompany")) {
    const hasRelativeValue = newData.hasRelativeInCompany;
    // 如果选择否，清空亲属姓名和亲属关系
    if (hasRelativeValue === "否" || !hasRelativeValue) {
      formData.relativeName = "";
      formData.relationshipType = "";
    }
  }
};

// 字段失焦处理
const handleFieldBlur = (fieldKey: string) => {
  validateField(fieldKey);
};

// 部门选择器变化处理
const handleDepartmentPickerChange = (
  fieldKey: string,
  value: string,
  _item: any,
) => {
  // XenDynamicFormCard组件会同时触发 @update:model-value 和 @change 事件
  // @update:model-value 已经通过 handleFormDataChange 设置了 formData[fieldKey] = value (部门ID)
  // 这里我们只需要保存部门ID到pickerValues中，用于提交到后端

  // 确保formData中存储的是部门ID（用于组件正确显示选中状态）
  formData[fieldKey] = value;

  // 同时保存到pickerValues中（用于提交到后端）
  pickerValues[fieldKey] = value;

  // 触发验证
  validateField(fieldKey);
};

// 部门选择器弹框打开处理
const handleDepartmentPickerOpen = () => {
  isDepartmentPickerOpen.value = true;
};

// 部门选择器弹框关闭处理
const handleDepartmentPickerClose = () => {
  isDepartmentPickerOpen.value = false;
};

// 自动补全变化处理
const handleAutoCompleteChange = (
  fieldKey: string,
  _value: string,
  option: any,
) => {
  console.log("自动补全变化处理:", fieldKey, _value, option);

  // 注意：不要在这里设置formData[fieldKey]，因为XenAutoComplete组件已经通过update:modelValue事件设置了
  // XenAutoComplete会：
  // 1. 显示option.text在输入框中
  // 2. emit update:modelValue(option.value) 设置formData[fieldKey] = option.value
  // 3. emit change事件到这里处理额外的逻辑

  if (option) {
    // 对于自动补全，formData中存储显示文本，pickerValues中存储实际值
    formData[fieldKey] = option.text;
    pickerValues[fieldKey] = option.value;
    console.log(`设置 formData[${fieldKey}] = ${option.text}`);
    console.log(`设置 pickerValues[${fieldKey}] = ${option.value}`);

    // 如果是招聘发布单选择，确保显示Title在输入框中
    if (fieldKey === "recruitPublishRequestBillId") {
      console.log("招聘发布单选择处理:", {
        text: option.text,
        value: option.value,
        subtitle: option.subtitle,
        extData: option.extData,
      });

      // 确保输入框显示的是Title（岗位标题）
      console.log(
        `招聘发布单输入框将显示: ${option.text} (来自Title: ${option.extData?.title})`,
      );

      // 验证option.text确实是Title
      if (option.extData?.title && option.text !== option.extData.title) {
        console.warn("警告：option.text 与 option.extData.title 不一致！");
        console.log("option.text:", option.text);
        console.log("option.extData.title:", option.extData.title);
      }

      if (option.subtitle) {
        // 从subtitle中提取单据编号，格式为 "单据编号: 12345 | 部门名称"
        const billCodeMatch = option.subtitle.match(/单据编号:\s*(\S+)/);
        if (billCodeMatch) {
          console.log("选择的招聘发布单编号:", billCodeMatch[1]);
        }
      }

      // 可以从扩展数据中获取更多信息
      if (option.extData) {
        console.log("招聘发布单详细信息:", option.extData);
        // 这里可以根据需要自动填入一些字段，比如岗位信息等
        // 例如：如果招聘发布单有关联的部门信息，可以自动设置
      }
    }
  } else {
    formData[fieldKey] = "";
    pickerValues[fieldKey] = "";
    console.log(`清空 formData[${fieldKey}] 和 pickerValues[${fieldKey}]`);

    // 如果清空招聘发布单选择，也清空相关字段
    if (fieldKey === "recruitPublishRequestBillId") {
      // 根据需要清空相关字段
      console.log("清空招聘发布单选择");
    }
  }

  // 触发验证
  validateField(fieldKey);
};

// 自动补全搜索处理
const handleAutoCompleteSearch = async (fieldKey: string, query: string) => {
  // 搜索逻辑已经在组件内部通过searchApi处理
  console.log("搜索:", fieldKey, query);
};

// 页面加载时获取路由参数
onLoad((options) => {
  console.log("应聘申请页面接收参数:", options);

  if (options) {
    // 处理招聘发布单ID
    if (options.recruitPublishId) {
      // 设置招聘发布单ID到表单数据
      pickerValues.recruitPublishRequestBillId = options.recruitPublishId;

      // 构建显示文本，优先使用招聘标题，如果没有则使用ID
      let displayText = options.recruitTitle
        ? decodeURIComponent(options.recruitTitle)
        : `招聘发布单-${options.recruitPublishId}`;
      formData.recruitPublishRequestBillId = displayText;

      console.log("设置招聘发布单:", {
        id: options.recruitPublishId,
        title: displayText,
        company: options.company ? decodeURIComponent(options.company) : "",
        department: options.department
          ? decodeURIComponent(options.department)
          : "",
      });
    }

    // 可以根据需要预填其他字段
    if (options.company) {
      console.log("预填公司信息:", decodeURIComponent(options.company));
    }

    if (options.department) {
      console.log("预填部门信息:", decodeURIComponent(options.department));
    }
  }
});

// 页面加载时获取数据
onMounted(async () => {
  // 初始化选项数据
  await initializeOptions();

  // 获取单据编号
  const billCode = await getBillCode();
  if (billCode) {
    formData.billCode = billCode;
  }
});

// 图片上传处理 (@select事件)
const handleImageUpload = async (field: any, event: any) => {
  // 图片上传逻辑
  console.log("图片上传:", field.key, event);

  const file = event.tempFiles?.[0] || event.tempFiles;
  const filePath = file?.path || file?.tempFilePath;

  if (filePath) {
    // 检查文件大小
    const maxSize = field.fileConfig?.maxSize || 5; // 默认5MB
    const fileSizeMB = file.size / (1024 * 1024);

    if (fileSizeMB > maxSize) {
      uni.showToast({
        title: `文件大小不能超过${maxSize}MB`,
        icon: "none",
        duration: 3000,
      });
      return;
    }

    // 如果是个人照片，特殊处理：阻止组件自动预览，等AI处理完成后再显示
    if (field.key === "photoId") {
      // 立即清空字段，阻止组件显示预览
      const newData = { ...formData, [field.key]: null };
      Object.assign(formData, newData);

      try {
        // 调用文件上传API获取fileId
        const fileId = await uploadImage(filePath);
        console.log(`${field.label}上传成功，文件ID:`, fileId);

        console.log("开始人像验证，图片ID:", fileId);
        const validateResult = await api.validatePortrait({ ImageId: fileId });
        console.log("人像验证结果:", validateResult);

        if (validateResult.Code !== 200) {
          // 验证失败，显示错误信息
          uni.showToast({
            title: validateResult.Message,
            icon: "none",
            duration: 3000,
          });
          // 不更新表单数据，保持字段为空
          return;
        } else {
          // 验证通过，显示成功提示
          uni.showToast({
            title: validateResult.Message,
            icon: "success",
            duration: 1500,
          });

          // 只使用处理后的图片ID
          if (validateResult.Data) {
            const processedImageId = validateResult.Data;
            console.log("使用处理后的图片ID:", processedImageId);
            // 更新表单数据为处理后的图片ID
            const finalData = { ...formData, [field.key]: processedImageId };
            Object.assign(formData, finalData);
          }
          return;
        }
      } catch (error) {
        console.error("人像验证失败:", error);
        uni.showToast({
          title: "照片验证失败，请重试",
          icon: "none",
          duration: 3000,
        });
        // 验证失败，不更新表单数据，保持空白
        return;
      }
    }

    // 其他字段的正常处理流程
    // 调用文件上传API获取fileId
    const fileId = await uploadImage(filePath);
    console.log(`${field.label}上传成功，文件ID:`, fileId);

    // 更新表单数据 - 使用响应式方式
    const newData = { ...formData, [field.key]: fileId };
    Object.assign(formData, newData);

    // 如果是身份证照片，触发OCR识别
    if (
      field.key === "idCardFrontPhotoId" ||
      field.key === "idCardBackPhotoId"
    ) {
      const cardType = field.key === "idCardFrontPhotoId" ? "front" : "back";
      await recognizeIdentityCard(fileId, cardType);
    }
  }
};

const handleImageSuccess = async (field: any, event: any) => {
  // 图片上传成功处理
  console.log("图片上传成功:", field.key, event);

  // 如果是个人照片（portrait-camera类型），进行人像验证
  if (field.key === "photoId" && field.type === "portrait-camera") {
    // 立即清空字段，阻止显示原始图片
    const clearData = { ...formData, [field.key]: null };
    Object.assign(formData, clearData);

    const fileId = event.fileId;
    if (fileId) {
      try {
        console.log("开始人像验证，图片ID:", fileId);
        const validateResult = await api.validatePortrait({ ImageId: fileId });
        console.log("人像验证结果:", validateResult);

        if (validateResult.Code !== 200) {
          // 验证失败，显示错误信息
          uni.showToast({
            title: validateResult.Message,
            icon: "none",
            duration: 3000,
          });
          // 保持字段为空
          return;
        } else {
          // 验证通过，显示成功提示
          uni.showToast({
            title: validateResult.Message,
            icon: "success",
            duration: 1500,
          });

          // 只使用处理后的图片ID
          if (validateResult.Data) {
            const processedImageId = validateResult.Data;
            console.log("使用处理后的图片ID:", processedImageId);
            // 更新表单数据为处理后的图片ID
            const finalData = { ...formData, [field.key]: processedImageId };
            Object.assign(formData, finalData);
          }
        }
      } catch (error) {
        console.error("人像验证失败:", error);
        uni.showToast({
          title: "照片验证失败，请重试",
          icon: "none",
          duration: 3000,
        });
        // 验证失败，保持字段为空
        return;
      }
    }
  }

  // 身份证识别已在 handleImageUpload 中处理
};

const handleImageFail = (_field: any, _event: any) => {
  // 图片上传失败处理
};

const handleImageDelete = (field: any, event: any) => {
  // 图片删除逻辑
  console.log("图片删除:", field.key, event);

  // 清空表单数据中对应的字段
  const newData = { ...formData, [field.key]: null };
  Object.assign(formData, newData);

  // 如果删除的是身份证照片，清空相关的识别字段
  if (field.key === "idCardFrontPhotoId") {
    Object.assign(formData, {
      name: "",
      gender: "",
      birthDate: "",
      ethnicity: "",
      idCardNo: "",
      householdRegistration: "",
      nativePlace: "",
    });
  } else if (field.key === "idCardBackPhotoId") {
    Object.assign(formData, {
      idCardExpiryDate: "",
    });
    // 重置身份证有效期显示状态
    idCardExpiryDisplayState.value = "normal";
  }
};

// 文件上传处理
const handleFileUpload = async (_field: any, _event: any) => {
  // 文件上传逻辑
};

const handleFileSuccess = (_field: any, _event: any) => {
  // 文件上传成功处理
};

const handleFileFail = (_field: any, _event: any) => {
  // 文件上传失败处理
};

const handleFileDelete = (_field: any, _event: any) => {
  // 文件删除处理
};

// 表单操作处理
const handleFormAction = (action: any) => {
  switch (action.key) {
    case "cancel":
      handleCancel();
      break;
    case "submit":
      handleSubmit();
      break;
    default:
      console.log("未知操作:", action.key);
  }
};

// 取消按钮
const handleCancel = () => {
  uni.navigateBack();
};

// 保存表单
const handleSubmit = async () => {
  uni.showLoading({ title: "保存中..." });

  // 使用Composable中的简单保存方法（只调用Add接口）
  const response = await saveInterviewSimple();

  uni.hideLoading();

  if (response.success && response.data && response.data.ID) {
    const recordId = response.data.ID;

    // 重新调用search接口获取最新的完整列表数据
    const searchResponse = await search({});
    if (searchResponse && searchResponse.length > 0) {
      // 发送完整列表数据更新事件
      InterviewInfoEvents.emit("refresh", {
        id: recordId,
        data: searchResponse,
        customAction: "add",
      });
    } else {
      // 如果获取失败，仍然发送简单的刷新事件作为备用方案
      InterviewInfoEvents.emit("refresh", {
        id: recordId,
        customAction: "add",
      });
    }

    uni.showToast({
      title: "保存成功",
      icon: "success",
      success: () => {
        setTimeout(() => {
          // 跳转到编辑页面，传递新创建的记录ID
          uni.redirectTo({
            url: `/subpkg-hr-syshrinterviewrequestbill/edit?id=${recordId}`,
            fail: () => {
              // 如果跳转失败，则返回上一页
              console.log("跳转编辑页失败，返回上一页");
              uni.navigateBack();
            },
          });
        }, 1000);
      },
    });
  } else {
    // 处理不同类型的错误信息
    let errorMessage = "保存失败，请重试";

    if (response.error) {
      // 显示具体的业务错误信息
      errorMessage = response.error;
    } else if (response.validation?.firstErrorMessage) {
      // 显示表单验证错误信息
      errorMessage = response.validation.firstErrorMessage;
    }

    uni.showToast({
      title: errorMessage,
      icon: "none",
      duration: 3000, // 延长显示时间，让用户能看清错误信息
    });
  }
};
</script>

<style lang="scss" scoped>
.form-container {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
  // 为固定底部按钮预留空间：按钮44px + 上下padding32px + 边框1px + 缓冲15px + 安全区域
  padding-bottom: calc(92px + constant(safe-area-inset-bottom));
  padding-bottom: calc(92px + env(safe-area-inset-bottom));
}
</style>
